<script setup>
import {ref, inject} from "vue";
import {Plus} from '@element-plus/icons-vue'
import {addPercentageInterval, INTERVAL_FIELD_NAME} from "@/utils/FileUtils.js";
import {FILE_URL_FIELD_NAME, fileUploadAPI, TIP_MSG_FIELD_NAME} from "@/api/file.js";
import {elErrorMessageTip, elSuccessMessageTip} from "@/utils/MessageTipUtils.js";
import {preview} from 'vue3-image-preview';
import {reactive} from "vue";
import {addBgAPI} from "@/api/bg.js";

// 是否显示
const {addBgVisible, search} = inject('addBgVisible')

const imgList = ref([])
const newImg = ref('')
const imgUpload = async (file, fileList) => {
  file = reactive(file)
  // fileList.value.push(file)
  fileList.value[0] = file
  file.status = 'uploading'
  // 文件上传进度计时器
  addPercentageInterval(file)
  // 文件上传
  const res = await fileUploadAPI(file.raw)
  if (res.status) {
    // 成功
    // 清除计时器
    clearInterval(file[INTERVAL_FIELD_NAME])
    elSuccessMessageTip(res[TIP_MSG_FIELD_NAME])
    file.status = 'success'
    file.percentage = 100
    file.url = res[FILE_URL_FIELD_NAME]
    newImg.value = file.url
  } else {
    // 失败
    // 清除计时器
    clearInterval(file[INTERVAL_FIELD_NAME])
    elErrorMessageTip(res[TIP_MSG_FIELD_NAME])
    file.status = 'fail'
    newImg.value = ''
  }
}
// 商品图片上传
const imgUploadHandler = (file) => {
  imgUpload(file, imgList)
}
const imgExceedHandler = (files) => {
  imgUpload({raw: files[0], percentage: 0}, imgList)
}
// 图片预览
const imgPreviewHandler = () => {
  preview({images: imgList.value, index: 0})
}
// 图片移除
const imgRemoveHandler = (index) => {
  newImg.value = ''
}

const addBg = async () => {
  if (newImg.value.length <= 0) {
    elErrorMessageTip('请先上传背景图片')
    return
  }
  const res = await addBgAPI(newImg.value)
  if (res) {
    // 关闭弹窗
    await search()
    newImg.value = ''
    imgList.value = []
    addBgVisible.value = false
  }
}
</script>

<template>
  <div class="add-authority">
    <el-dialog v-model="addBgVisible" title="新增背景图片" width="30%">
      <div class="p-2">
        <el-upload
            v-model:file-list="imgList"
            list-type="picture-card"
            :auto-upload="false"
            :limit="1"
            :on-remove="imgRemoveHandler"
            :on-exceed="imgExceedHandler"
            :on-change="imgUploadHandler"
            :on-preview="imgPreviewHandler"
        >
          <el-icon>
            <Plus/>
          </el-icon>
        </el-upload>
      </div>
      <div class="mt-8">
        <el-button type="primary" plain @click="addBg">添加背景图片</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped>

</style>